package ar.uade.distribuidas.tpo.srv.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import ar.uade.distribuidas.tpo.base.dominiodto.ListaPrecioDTO;
import ar.uade.distribuidas.tpo.srv.dao.ListaPrecioXmlDAO;
import ar.uade.distribuidas.tpo.srv.delegado.BD;

/**
 * Servlet implementation class AltaListaPrecio
 */
@WebServlet("/AltaListaPrecio")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class AltaListaPrecio extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AltaListaPrecio() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("WEB-INF/jsp/asiglisp.jsp");

		String proveedor = request.getParameter("cuil");
		Part parteArch = request.getPart("file");
		InputStream filecontent = parteArch.getInputStream();
		ListaPrecioXmlDAO lpDAO = ListaPrecioXmlDAO.getInstancia(filecontent);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		Document doc;
		try {
			builder = factory.newDocumentBuilder();
			doc = builder.parse(filecontent);

			List<ListaPrecioDTO> listas = lpDAO.recuperarListaPrecio(doc);

			// try{
			for (ListaPrecioDTO ldto : listas) {
				BD.getInstance().altaListaPrecio(ldto);
			}

			request.setAttribute("allok",
					"La solicitud fue procesada correctamente.");
			request.getRequestDispatcher("/jsp/asiglisp.jsp").forward(request,
					response);

			//System.out.println("me fui por el try");
		} catch (Exception e) {
			request.setAttribute("allerror",
					"Hubo un error al procesar la solicitud.");
			request.getRequestDispatcher("/jsp/asiglisp.jsp").forward(request,
					response);
			e.printStackTrace();
			//System.out.println("me fui por el catch");
		}
	}

}
